package com.kjsdfgk.hjmdsf.play.mvp.presenter;

import android.app.Application;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.TimeUtils;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;

import javax.inject.Inject;

import com.jess.arms.utils.RxLifecycleUtils;
import com.kjsdfgk.hjmdsf.app.entity.HistoryItem;
import com.kjsdfgk.hjmdsf.app.entity.XJVideoJson;
import com.kjsdfgk.hjmdsf.ftvdolist.mvp.bean.XJLookResult;
import com.kjsdfgk.hjmdsf.ftvdolist.mvp.bean.XJResult;
import com.kjsdfgk.hjmdsf.play.mvp.contract.MyPlayVideoContract;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/10/2020 12:30
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class MyPlayVideoPresenter extends BasePresenter<MyPlayVideoContract.Model, MyPlayVideoContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public MyPlayVideoPresenter(MyPlayVideoContract.Model model, MyPlayVideoContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void lookVod(int vodId) {

        String uid="8517369";

        final String key = new Date().toString();

        mModel.lookVod(uid,vodId)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> mRootView.showLoading(key))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<XJLookResult>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                        mRootView.hideLoading();
                        mRootView.showMessage("服务器繁忙 ，请稍后在试！");

                    }

                    @Override
                    public void onNext(@NonNull XJLookResult result) {
                        mRootView.hideLoading();
                        if (result.getInfo().getPlayer_list()!=null && result.getInfo().getPlayer_list().size() >0){
                            mRootView.playVideo(result.getInfo().getPlayer_list());
                        } else {
                            mRootView.showMessage("数据解析错误 ，无法播放");
                        }


                    }
                });
    }

    public void lookVod(String href) {
        final String key = new Date().toString();
        mModel.ccyyHtml(href)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> mRootView.showLoading(key))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                        mRootView.hideLoading();
                        mRootView.showMessage("服务器繁忙 ，请稍后在试！");

                    }

                    @Override
                    public void onNext(@NonNull String result) {
                        mRootView.hideLoading();

                        mRootView.playVideo(href.contains("hsck") ?parseHSCK(result): parseCCYYHtml(result) );


                    }
                });

    }

    private List<XJLookResult.InfoBean.PlayerListBean> parseCCYYHtml(String result ) {
        try {
            List<XJLookResult.InfoBean.PlayerListBean> listBeans = new ArrayList<>();
//            Jsoup.parse(result).getAllElements().select("div").get(2).attributes().get("class")
            for (Element element : Jsoup.parse(result).getAllElements().select("div")){

                if ("myplayer".equals(element.attributes().get("class"))){


                    XJLookResult.InfoBean.PlayerListBean bean = new XJLookResult.InfoBean.PlayerListBean();

                    bean.setUrl(element.childNode(1).attr("src").split("url=")[1]);

                    listBeans.add(bean);
                }



            }
            return listBeans;
        }catch (Exception e){
            mRootView.showMessage(e.toString());
        }
        return null;
    }

    private List<XJLookResult.InfoBean.PlayerListBean> parseHSCK(String result ) {
        try {
            List<XJLookResult.InfoBean.PlayerListBean> listBeans = new ArrayList<>();

            for (Element element : Jsoup.parse(result).getAllElements().select("div")){

                if ("stui-player__video clearfix".equals(element.attributes().get("class"))){

                    XJLookResult.InfoBean.PlayerListBean bean = new XJLookResult.InfoBean.PlayerListBean();

                    bean.setUrl( JSON.parseObject(element.childNode(1).childNode(0).toString().split("=")[1]).getString("url"));

                    listBeans.add(bean);
                }



            }
            return listBeans;
        }catch (Exception e){
            mRootView.showMessage(e.toString());
        }
        return null;
    }
}
